﻿using CXW.Core.Sharp.Services;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Windows.Forms;

namespace CXW.Core.Sharp.Gui
{
    class TreeViewExt : TreeView
    {
        List<TreeNode> _nodes = new List<TreeNode>();
        object owner = null;
        public TreeViewExt()
        {
            Dock = DockStyle.Fill;

            BeforeExpand += (sender, e) => { if (e.Node != null) { UpdateText(e.Node.Nodes); } };

            NodeMouseDoubleClick += (sender, e) =>
            {//只有纯子节点才有双击节点事件处理
                if (e.Node.Nodes.Count == 0 && !_nodes.Contains(e.Node))
                {
                    ICommand cmd = CommandWrapper.CreateCommand(e.Node.Tag as Codon, owner);
                    if (cmd == null) { _nodes.Add(e.Node); e.Node.ForeColor = System.Drawing.Color.Gray; }
                    else { cmd.Run(); }
                }
            };
        }

        public TreeViewExt(IList Items) : this()
        {
            Nodes.AddRange(CreatedNode(Items));
        }
        public TreeViewExt(IList Items, object owner) : this(Items)
        {
            this.owner = owner;
        }
        TreeNode[] CreatedNode(IList Items)
        {
            List<TreeNode> nodes = new List<TreeNode>();
            foreach (IItemDescriptor des in Items)
            {
                TreeNode node = CreatedNode(des.Codon);
                nodes.Add(node);
                node.Nodes.AddRange(CreatedNode(des.SubItems));
            }

            return nodes.ToArray();
        }

        TreeNode CreatedNode(Codon codon)
        {
            string type = codon.Properties.Contains("type") ? codon.Properties["type"] : "TreeNode";
            if (type != "TreeNode") { throw new NotSupportedException("unsupported TreeItem type : " + type); }

            return new TreeNode()
            {
                Tag = codon,
                Text = LanguageHelper.GetText(codon),
                Name = codon.Id,
                ToolTipText = LanguageHelper.GetText(codon)
            };
        }

        public static void UpdateText(TreeNodeCollection nodes)
        {
            foreach (TreeNode node in nodes)
            {
                node.Text = LanguageHelper.GetText(node.Tag as Codon);
                if (node.IsExpanded)
                {
                    UpdateText(node.Nodes);
                }
            }
        }
    }
}
